package com.example.myapplication.utils;

import android.content.Context;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;


public class ImageLoader {

    // 加载图片，自动判断是网络图片还是本地图片
    public static void load(Context context, String path, ImageView imageView, int placeholderResId, int errorResId) {
        RequestOptions options = new RequestOptions()
                .placeholder(placeholderResId)
                .error(errorResId);

        if (isNetworkPath(path)) {
            // 如果是网络路径
            Glide.with(context)
                    .load(path)
                    .apply(options)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(imageView);
        } else {
            // 如果是本地路径
            int resourceId = context.getResources().getIdentifier(
                    path,
                    "drawable",
                    context.getPackageName()
            );

            Glide.with(context)
                    .load(resourceId)
                    .apply(options)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(imageView);
        }
    }

    // 判断是否是网络路径
    private static boolean isNetworkPath(String path) {
        return path.startsWith("http://") || path.startsWith("https://");
    }
}
